from django.forms.models import model_to_dict
from BloodSpiderAPI.models import OrderList, SubOrder


# 模型转字典
def utils_model_to_dict(model, *args, **kwargs):
    data = model_to_dict(model)
    
    # 转换UUID类型的字段为字符串
    if hasattr(model, 'order_id'):
        # 处理SubOrder中的order_id外键字段
        if hasattr(model, 'sub_order_id'):  # 如果是SubOrder模型
            data["order_id"] = str(model.order_id.order_id)  # 获取关联对象的UUID字符串
        else:  # 如果是OrderList模型
            data["order_id"] = str(model.order_id)
    if hasattr(model, 'sub_order_id'):
        data["sub_order_id"] = str(model.sub_order_id)
    
    # 处理时间格式
    if kwargs.get("show_time", True):
        if hasattr(model, 'create_time'):
            data["create_time"] = model.create_time.strftime("%Y-%m-%d %H:%M:%S")
        if hasattr(model, 'update_time'):
            data["update_time"] = model.update_time.strftime("%Y-%m-%d %H:%M:%S")
    
    return data


# 获取订单详情（包含子订单）
def get_order_detail(order_id):
    try:
        order = OrderList.objects.get(order_id=order_id)
        order_data = utils_model_to_dict(order)
        
        # 获取关联的子订单并确保子订单列表不为None
        sub_orders = SubOrder.objects.filter(order_id=order_id) or []
        order_data['sub_orders'] = [utils_model_to_dict(sub_order) for sub_order in sub_orders]
        
        return order_data
    except OrderList.DoesNotExist:
        return None